package top.mccat.shirospring.shiro.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import top.mccat.shirospring.shiro.realm.UserRealm;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * @author raven
 */
@Configuration
public class ShiroConfig {
    @Bean
    public UserRealm userRealm(){
        return new UserRealm();
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(UserRealm userRealm){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(userRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(DefaultWebSecurityManager manager){
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(manager);
        //进行地址拦截
        Map<String,String> filterMap = new LinkedHashMap<>();
        filterMap.put("/modify/add","perms[user:add]");
        filterMap.put("/modify/drop","perms[user:drop]");
        filterMap.put("/modify/*","authc");
        shiroFilterFactoryBean.setFilterChainDefinitionMap(filterMap);
        //如果没有权限则跳转到login界面
        shiroFilterFactoryBean.setLoginUrl("/toLogin");
        shiroFilterFactoryBean.setUnauthorizedUrl("/noauth");
        return shiroFilterFactoryBean;
    }

    @Bean
    public ShiroDialect getShiroDialect(){
        return new ShiroDialect();
    }
}
